package com.qin.mall.controller.userController;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qin.mall.common.api.MyBatisPlusPage;
import com.qin.mall.domain.UmsAdmin;
import com.qin.mall.domain.UmsRole;
import com.qin.mall.common.api.CommonResult;
import com.qin.mall.common.domain.UserDto;
import com.qin.mall.dto.UmsAdminLoginParam;
import com.qin.mall.dto.UmsAdminParam;
import com.qin.mall.dto.UpdateAdminPasswordParam;
//import com.qin.mall.result.CommonResult;
import com.qin.mall.service.UmsAdminService;
import com.qin.mall.service.UmsRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 后台用户管理
 * @author Leisure
 * create 2022 2022/11/11 10:08
 **/
@RestController
@RequestMapping("/admin")
public class UmsAdminController {
    @Value("${jwt.tokenHeader}")
    private String tokenHeader;
    @Value("${jwt.tokenHead}")
    private String tokenHead;
    
    @Autowired
    private UmsAdminService adminService;
    @Autowired
    private UmsRoleService roleService;

    /**
     * 根据用户名获取通用用户信息
     */
    @GetMapping("/loadByUsername")
    @ResponseBody
    public UserDto loadUserByUsername(@RequestParam String username){
        UserDto userDTO = adminService.loadUserByUsername(username);
        return userDTO;
    }   
    
    /**
     * 用户注册
     */
    @PostMapping("/register")
    public CommonResult<UmsAdmin> register(@RequestBody UmsAdminParam umsAdminParam){
        UmsAdmin register = adminService.register(umsAdminParam);
        if (register == null) {
            return CommonResult.failed();
        }
        return CommonResult.success(register);
    }

    /**
     * 用户登陆，登陆后返回token
     */
    @PostMapping("/login")
    public CommonResult login(@RequestBody UmsAdminLoginParam umsAdminLoginParam){
        CommonResult login = adminService.login(umsAdminLoginParam.getUsername(), umsAdminLoginParam.getPassword());
        return login;

    }

    /**
     * 刷新token
     */
    @GetMapping("/refreshToken")
    public CommonResult refreshToken(HttpServletRequest request){
        String token = request.getHeader(tokenHeader);
        String refreshToken = adminService.refreshToken(token);
        if (refreshToken == null) {
            return CommonResult.failed("token已经过期！");
        }
        Map<String, String> tokenMap = new HashMap<>();
        tokenMap.put("token", refreshToken);
        tokenMap.put("tokenHead", tokenHead);
        return CommonResult.success(tokenMap);
        
    }

    /**
     * 获取当前登录用户信息
     * Principal 这个接口包含了获取用户的基本信息
     * 这个Principal 跟UserDetails 有关
     * 我们有一个实现类跟UserDetails 有关
     */
    @GetMapping("/info")
    @ResponseBody
    public CommonResult getAdminInfo(){
        UmsAdmin umsAdmin = adminService.getCurrentAdmin();
        Map<String, Object> data = new HashMap<>();
        data.put("username", umsAdmin.getUsername());
        data.put("menus", roleService.getMenuList(umsAdmin.getId()));
        data.put("icon", umsAdmin.getIcon());
        List<UmsRole> roleList = adminService.getRoleList(umsAdmin.getId());
        if(CollUtil.isNotEmpty(roleList)){
            List<String> roles = roleList.stream().map(UmsRole::getName).collect(Collectors.toList());
            data.put("roles",roles);
        }
        return CommonResult.success(data);
    }

    /**
     * 登出功能
     */
    @PostMapping("/logout")
    public CommonResult logout(){
        return CommonResult.success(null);
    }

    /**
     * 获取指定用户信息
     */
    @GetMapping("/{id}")
    public CommonResult<UmsAdmin> getItem(@PathVariable Long id){
        UmsAdmin admin = adminService.getItem(id);
        return CommonResult.success(admin);
    }

    /**
     * 修改指定用户信息
     */
    @PostMapping("/update/{id}")
    public CommonResult update(@PathVariable  Long id,
                               @RequestBody UmsAdmin admin){
        int count = adminService.update(id, admin);
        if (count > 0) {
            return CommonResult.success(count);
        }
        return CommonResult.failed();
    }


    /**
     * 修改指定用户密码
     */
    @PostMapping("/updatePassword")
    public CommonResult updatePassword(@RequestBody UpdateAdminPasswordParam updatePasswordParam){
        int status = adminService.updatePassword(updatePasswordParam);
        if (status > 0) {
            return CommonResult.success(status);
        } else if (status == -1) {
            return CommonResult.failed("提交参数不合法");
        } else if (status == -2) {
            return CommonResult.failed("找不到该用户");
        } else if (status == -3) {
            return CommonResult.failed("旧密码错误");
        } else {
            return CommonResult.failed();
        }
    }

    /**
     * 删除指定用户信息
     */
    @PostMapping("/delete/{id}")
    public CommonResult delete(@PathVariable Long id){
        int count = adminService.delete(id);
        if (count > 0) {
            return CommonResult.success(count);
        }
        return CommonResult.failed();
    }

    /**
     * 修改帐号状态
     */
    @PostMapping("/updateStatus/{id}")
    @ResponseBody
    public CommonResult updateStatu(@PathVariable Long id,
                                    @RequestParam("status") Integer status){
        UmsAdmin umsAdmin = new UmsAdmin();
        umsAdmin.setStatus(status);
        int count = adminService.update(id,umsAdmin);
        if (count > 0) {
            return CommonResult.success(count);
        }
        return CommonResult.failed();
    }

    /**
     * 给用户分配角色
     */
    @PostMapping("/role/update")
    public CommonResult updateRole(@RequestParam("adminId") Long adminId,
                                   @RequestParam("roleIds") List<Long> roleIds){
        int count = adminService.updateRole(adminId, roleIds);
        if (count >= 0) {
            return CommonResult.success(count);
        }
        return CommonResult.failed();
    }

    /**
     * 获取指定用户的角色
     */
    @GetMapping("/role/{adminId}")
    public CommonResult<List<UmsRole>> getRoleList(@PathVariable  Long adminId){
        List<UmsRole> roleList = adminService.getRoleList(adminId);
        return CommonResult.success(roleList);
    }

    /**
     * 根据用户名或姓名分页获取用户列表
     */
    @GetMapping("/list")
    @ResponseBody
    public CommonResult<MyBatisPlusPage<UmsAdmin>> list(@RequestParam(value = "keyword", required = false) String keyword,
                                                        @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize,
                                                        @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum) {
        List<UmsAdmin> adminList = adminService.list(keyword, pageSize, pageNum);
        return CommonResult.success(MyBatisPlusPage.getPages(pageNum.longValue(),pageSize.longValue(),adminList));
    }
}
